//
//  SY_Tch_AttendanceViewController.m
//  ChatDemo-UI2.0
//
//  Created by Sylar on 2017/2/10.
//  Copyright © 2017 Sylar. All rights reserved.
//

#import "SY_Tch_AttendanceViewController.h"
#import "FDCalendar.h"
#import "SY_AttendanceAccountViewController.h"
#import "SY_AttendanceStudentCell.h"
@interface SY_Tch_AttendanceViewController ()<UIPickerViewDataSource,UIPickerViewDelegate,UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    
    UIControl *control;
    UIButton *sureBtn;
    
    BOOL flag;
    NSInteger count;
    
    EmptyStateView *emptyView;
    
    UILabel *dateLabel;
}

@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) UIButton *moreButton;
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) UIButton *classBtn;
@property (nonatomic, strong) UIButton *dateBtn;
@property (nonatomic, strong) UIButton *chooseAllBtn;
@property (nonatomic, strong) UIPickerView *classPicker;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIImageView *selectAllImg;

@property (nonatomic, strong) NSDictionary *classInfoDic;
@property (nonatomic, copy)   NSString  *classid;
@property (nonatomic, strong) NSMutableArray *classNames; //存放班级名称
@property (nonatomic, strong) NSMutableArray *classesArr; //存放班级
@property (nonatomic,assign)  NSInteger indexOfType;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) NSArray *studentArr;
@property (nonatomic, strong) NSMutableArray *selectArr;//已选学生

@end

@implementation SY_Tch_AttendanceViewController

- (void)loadView {
    
    [super loadView];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"到校",@"离校"]];
    [self.segment addTarget:self action:@selector(segmentChange:) forControlEvents:(UIControlEventValueChanged)];
    self.segment.size = CGSizeMake(194, 26);
    self.segment.center = CGPointMake(SCREENWIDTH/2,SafeAreaTopHeight - 26);
    self.segment.selectedSegmentIndex = 0;
    self.segment.tintColor = colorFromHex(@"#1ebfff");
    
    UIFont *font = [UIFont systemFontOfSize:15.0f];
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                                           forKey:NSFontAttributeName];
    [self.segment setTitleTextAttributes:attributes
                                forState:UIControlStateNormal];
    
    [self.navBar addSubview:self.segment];
    
    self.type = 1;
    flag = YES;

//   self.navBar.rightImg.hidden = NO;
//   self.navBar.rightButton.hidden = NO;
//
//   self.navBar.rightImg.image = [UIImage imageNamed:@"ios_more_"];
//    [self.navBar.rightButton addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
   
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    
    self.segment.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:YES];
    
    self.segment.hidden = YES;
//    [self.segment removeFromSuperview];
//    self.segment = nil;
}

- (void)dealloc {
    
    self.segment = nil;
    [self.segment removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    emptyView = [[EmptyStateView alloc] initWithFrame:CGRectMake((SCREENWIDTH-120)/2, (SCREENHEIGH-110)/2-70, 120, 110) andBackImage:@"list_empty" andBottomStr:@"班级暂无宝宝"];
    [self.view addSubview:emptyView];
    
    [self.view addSubview:self.classBtn];
    [self.view addSubview:self.myTableView];
    
    [self setUpBottomView];
    
    dateLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREENWIDTH - 165, 17 + SafeAreaTopHeight, 150, 16)];
    [dateLabel setFont:[UIFont systemFontOfSize:16]];
    [dateLabel setTextColor:colorFromHex(@"#3b3b3b")];
    dateLabel.textAlignment = NSTextAlignmentRight;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
    dateLabel.text = [formatter stringFromDate:[NSDate date]];
    
    
    [self.view addSubview:dateLabel];
    
    [self loadAllClassData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Method

- (void)setUpBottomView {
    
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGH - 114-SafeAreaBottomHeight, SCREENWIDTH, 114)];
    [self.bottomView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.bottomView];
    
    
    sureBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [sureBtn setFrame:CGRectMake(0, 50, 180, 40)];
    sureBtn.centerX = self.bottomView.centerX;
    sureBtn.layer.cornerRadius = 20;
    [sureBtn setBackgroundColor:colorFromHex(@"#1ebfff")];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [sureBtn setTitle:@"确认到校" forState:(UIControlStateNormal)];
    [sureBtn addTarget:self action:@selector(makeSureAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.bottomView addSubview:sureBtn];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(SCREENWIDTH - 50, 20, 35, 16)];
    label1.text = @"全选";
    label1.textColor = colorFromHex(@"#3b3b3b");
    [label1 setFont:[UIFont systemFontOfSize:16]];
    [self.bottomView addSubview:label1];
    
    self.selectAllImg = [[UIImageView alloc]initWithFrame:CGRectMake(label1.x - 25, 16, 20, 20)];
    [self.selectAllImg setImage:[UIImage imageNamed:@"homeworks_allchoose_press_"]];
    [self.bottomView addSubview:self.selectAllImg];
    
    UIButton *allBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [allBtn setFrame:CGRectMake(SCREENWIDTH - 80, 10, 80, 26)];
    [allBtn addTarget:self action:@selector(quanxuanAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.bottomView addSubview:allBtn];
    
}


#pragma mark - SegmentedControl Actions

- (void)segmentChange:(UISegmentedControl *)segment {
    
    
    if (segment.selectedSegmentIndex == 0) {
        self.type = 1;
        [sureBtn setTitle:@"确认到校" forState:(UIControlStateNormal)];
    }else {
        self.type = 2;
        [sureBtn setTitle:@"确认离校" forState:(UIControlStateNormal)];
    }
}

#pragma mark - Action

-(void)quanxuanAction:(UIButton *)sender
{
    flag=!flag;
    if (flag==YES) {
        
        [self.selectAllImg setImage:[UIImage imageNamed:@"homeworks_allchoose_press_"]];
        count=(int)self.selectArr.count;
        if (self.selectArr.count>0) {
            for ( int i=0; i<[self.selectArr count]; i++) {
                NSDictionary *dic=[self.selectArr objectAtIndex:i];
                NSMutableDictionary *mudic=[NSMutableDictionary dictionaryWithDictionary:dic];
                [mudic setObject:@"1" forKey:@"check"];
                [self.selectArr replaceObjectAtIndex:i withObject:mudic];
            }
        }
        
    }else
    {
        [self.selectAllImg setImage:[UIImage imageNamed:@"homeworks_allchoose_nor_"]];
        count=0;
        if (self.selectArr.count>0)
        {
            for ( int i=0; i<[self.selectArr count]; i++) {
                NSDictionary *dic=[self.selectArr objectAtIndex:i];
                NSMutableDictionary *mudic=[NSMutableDictionary dictionaryWithDictionary:dic];
                [mudic setObject:@"0" forKey:@"check"];
                [self.selectArr replaceObjectAtIndex:i withObject:mudic];
            }
        }
    }
    [self.myTableView reloadData];
}

//确定到校离校
- (void)makeSureAction {
    
    NSMutableArray *XIDArray=[NSMutableArray array];
    NSMutableArray *WIDArray=[NSMutableArray array];
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"sy_rollcall_add" forKey:@"method"];
    [dict setObject:self.classid forKey:@"classid"];
    [dict setObject:USERID  forKey:@"teacherid"];
    for (int i=0; i<[self.selectArr count]; i++) {
       
       NSInteger  check = [[[self.selectArr objectAtIndex:i] objectForKey:@"check"] integerValue];
       
        if (check == 1) {
           
            [XIDArray addObject:[[self.selectArr objectAtIndex:i] objectForKey:@"studentid"]];
        }else
        {
            [WIDArray addObject:[[self.selectArr objectAtIndex:i] objectForKey:@"studentid"]];
        }
    }
    NSString *gouxuanStr=[XIDArray componentsJoinedByString:@","];
    NSString *wgouxuanStr=[WIDArray componentsJoinedByString:@","];
    if ([XIDArray count]>0) {
        [dict setObject:gouxuanStr forKey:@"stuedentid1"];
    }else
    {
//        [Utils alertViewWithMessage:@"请选择学生进行操作!"];
//        return;
    }
    if ([WIDArray count]>0) {
        [dict setObject:wgouxuanStr forKey:@"stuedentid2"];
    }
    [dict setObject:[NSString stringWithFormat:@"%ld",self.type] forKey:@"type"];
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        NSDictionary *dict = (NSDictionary *)resposeJson;
        [Utils alertViewWithMessage:[dict objectForKey:@"re_info"]];
    } failure:^(NSInteger recode, NSError * error){
        
    }];
    
    
}

- (void)cancelControlAction
{
    [control removeFromSuperview];
}

- (void)chooseTypeAction:(UIButton *)sender
{
    [control removeFromSuperview];
    
    if (sender.tag == 1) {
        
        [self.classesArr objectAtIndex:_indexOfType];
        
        self.classid = [NSString stringWithFormat:@"%@",[[self.classesArr objectAtIndex:_indexOfType] objectForKey:@"classid"]];
        self.classInfoDic = [self.classesArr objectAtIndex:_indexOfType];
        
        [self.classBtn setTitle:[self.classNames objectAtIndex:_indexOfType] forState:(UIControlStateNormal)];
        [self loadStudentsDate];
        
    }
    
}

//更多
//- (void)moreAction {
//    
//    SY_AttendanceAccountViewController *moreVC = [[SY_AttendanceAccountViewController alloc]init];
//    
//    [self.navigationController pushViewController:moreVC animated:YES];
//    
//}

- (void)chooseClass {
    
    [control removeFromSuperview];
    control=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH)];
    control.backgroundColor=[UIColor clearColor];
    [control addTarget:self action:@selector(cancelControlAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *doneBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    doneBtn.frame=CGRectMake(SCREENWIDTH-12-40,SCREENHEIGH-200, 40, 30);
    [doneBtn setTitle:@"完成" forState:UIControlStateNormal];
    [doneBtn setTitleColor:RGBACOLOR(57, 173, 255, 1) forState:UIControlStateNormal];
    [doneBtn addTarget:self action:@selector(chooseTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    doneBtn.tag = 1;
    
    [control addSubview:doneBtn];
    
    [control addSubview:self.classPicker];
    
    UIWindow *window = KeyWindow;
    [window addSubview:control];
    
}

- (void)chooseDate {
    
}

#pragma mark - Request

//加载班级
- (void)loadAllClassData {
    
    BaseModel *param = [BaseModel param];
    param.method = @"sy_rollcall_classlist";
    param.teacherid = USERID;
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSArray *arr = [jsonObject objectForKey:@"re_data"];
        
        for (NSDictionary *dic in arr) {
            
            [self.classesArr addObject:dic];
        }
        
        if (self.classesArr.count == 0) {  //没有班级
            
            [self.classBtn removeFromSuperview];
            [self.myTableView removeFromSuperview];
            self.moreButton.hidden = YES;
            [self->dateLabel removeFromSuperview];
            [self.bottomView removeFromSuperview];
            
            EmptyStateView *emptyView1 = [[EmptyStateView alloc] initWithFrame:CGRectMake(0, (SCREENHEIGH-110)/2-70, SCREENWIDTH, 110) andBackImage:@"list_empty" andBottomStr:@"此功能仅班主任可用"];
            [self.view addSubview:emptyView1];
            [emptyView1 showEmptyImage];
            
            
        }else if(self.classesArr.count > 0){ //有班级
            
            
            for (NSDictionary *dic in self.classesArr) {
                
                NSString *className = [dic objectForKey:@"classname"];
                
                [self.classNames addObject:className];
            }
            
            self.classid = [NSString stringWithFormat:@"%@",[[self.classesArr objectAtIndex:0] objectForKey:@"classid"]];
            self.classInfoDic = [self.classesArr objectAtIndex:0];
            
            [self.classBtn setTitle:[self.classNames firstObject] forState:(UIControlStateNormal)];
            
            [self loadStudentsDate];
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

- (void)loadStudentsDate {
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"sy_rollcall_studentlist" forKey:@"method"];
    [dict setObject:self.classid forKey:@"classid"];
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        self.studentArr = [[NSArray alloc]init];
        self.selectArr = [[NSMutableArray alloc]init];
        
        NSDictionary *dict = (NSDictionary *)resposeJson;
        
        self.studentArr = [dict objectForKey:@"re_data"];
        self.selectArr = [NSMutableArray arrayWithArray:self.studentArr];
        
        self->flag = YES;
        [self.selectAllImg setImage:[UIImage imageNamed:@"homeworks_allchoose_press_"]];
        self->count = self.selectArr.count;
        
        if (self->count > 0) {
            
            self.bottomView.hidden = NO;
            self.myTableView.hidden = NO;
            [self.myTableView reloadData];
            
        }else {
            
            self.bottomView.hidden = YES;
            self.myTableView.hidden = YES;
            [self->emptyView showEmptyImage];
        }
        
        
    } failure:^(NSInteger recode, NSError * error){
        
        
    }];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.studentArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SY_AttendanceStudentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    
    if (cell == nil) {
        cell = [[SY_AttendanceStudentCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cellIdentifier"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    for (UIView *view in cell.contentView.subviews) {
        if (view.tag == 50) {
            [view removeFromSuperview];
        }
    }
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(15, 43.5, SCREENWIDTH, 0.5)];
    [lineView setBackgroundColor:colorFromHex(@"#DEDEDE")];
    lineView.tag = 50;
    [cell.contentView addSubview:lineView];
    
    if (indexPath.row == self.selectArr.count-1) {
        lineView.x = 0;
    }else {
        lineView.x = 15;
    }
    
    [cell ceratCell:[self.selectArr objectAtIndex:indexPath.row]];
    
    return cell;
     
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SY_AttendanceStudentCell *cell=[tableView cellForRowAtIndexPath:indexPath];
   NSString *check= [NSString stringWithFormat:@"%@",[[self.selectArr objectAtIndex:indexPath.row]objectForKey:@"check"]];
   
    if ([check isEqualToString:@"1"]) {
        
        count--;
        flag = NO;
        check=@"0";
        NSDictionary *dic=[self.selectArr objectAtIndex:indexPath.row];
        NSMutableDictionary *mudic=[NSMutableDictionary dictionaryWithDictionary:dic];
        [mudic setObject:check forKey:@"check"];
        [self.selectArr replaceObjectAtIndex:indexPath.row withObject:mudic];
        check=[[self.selectArr objectAtIndex:indexPath.row]objectForKey:@"check"];
        [self.selectAllImg setImage:[UIImage imageNamed:@"homeworks_allchoose_nor_"]];
        
    }else
    {
        count++;
        check=@"1";
        NSDictionary *dic=[self.selectArr objectAtIndex:indexPath.row];
        NSMutableDictionary *mudic=[NSMutableDictionary dictionaryWithDictionary:dic];
        [mudic setObject:check forKey:@"check"];
        [self.selectArr replaceObjectAtIndex:indexPath.row withObject:mudic];
        check=[[self.selectArr objectAtIndex:indexPath.row]objectForKey:@"check"];
        if (count==[self.selectArr count]) {
            [self.selectAllImg setImage:[UIImage imageWithOriginalName:@"homeworks_allchoose_press_"]];
            flag=YES;
        }
    }
    if ([check isEqualToString:@"1"]) {
        [cell.cheakImg setImage:[UIImage imageWithOriginalName:@"homeworks_allchoose_press_"]];
    }else
    {
        [cell.cheakImg setImage:[UIImage imageWithOriginalName:@"homeworks_allchoose_nor_"]];
    }
}

#pragma mark - PickerDelegate & PickerDataSource

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    if (pickerView == self.classPicker) {
        return 1;
    }
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    if (pickerView == self.classPicker) {
        return self.classesArr.count;
    }
    
    return 0;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (pickerView == self.classPicker) {
        return [self.classNames objectAtIndex:row];
    }
    
    return nil;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (pickerView == self.classPicker) {
        self.indexOfType = row;
    }
}

-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    
    return 200;
}

#pragma mark = AlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    [self.navigationController popViewControllerAnimated:YES];
}






#pragma mark - Get

- (UITableView *)myTableView {
    
    if (_myTableView == nil) {
        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50 + SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-50-114-SafeAreaBottomHeight-SafeAreaTopHeight)];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableView.rowHeight = 44;
        [_myTableView setBackgroundColor:colorFromHex(@"#F5F8FA")];
    }
   
    return _myTableView;
}

- (UIButton *)classBtn {
    
    if (_classBtn == nil) {
        _classBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_classBtn setFrame:CGRectMake(15, 12 + SafeAreaTopHeight, 92, 26)];
        _classBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        _classBtn.layer.borderWidth = 0.5;
        _classBtn.layer.cornerRadius = 4;
        _classBtn.layer.borderColor = [colorFromHex(@"#1EBFFF") CGColor];
        [_classBtn setBackgroundColor:colorFromHex(@"#E6F6FC")];
        [_classBtn setTitleColor:colorFromHex(@"#1EBFFF") forState:(UIControlStateNormal)];
        [_classBtn addTarget:self action:@selector(chooseClass) forControlEvents:(UIControlEventTouchUpInside)];
        
        
    }
    return _classBtn;
}

- (UIButton *)dateBtn {
    
    if (_dateBtn == nil) {
        _dateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_dateBtn setFrame:CGRectMake(SCREENWIDTH - 165, 12, 150, 44)];
//        _dateBtn.layer.borderWidth = 1;
//        _dateBtn.layer.cornerRadius = 5;
        [_dateBtn addTarget:self action:@selector(chooseDate) forControlEvents:(UIControlEventTouchUpInside)];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy年MM月dd日"];
        
        NSString *dateStr = [formatter stringFromDate:[NSDate date]];
        [_dateBtn setTitle:dateStr forState:(UIControlStateNormal)];
        [_dateBtn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    }
    return _dateBtn;
}

- (UIPickerView *)classPicker {
    
    if (_classPicker == nil) {
        _classPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SCREENHEIGH-170, SCREENWIDTH, 170)];
        _classPicker.delegate = self;
        _classPicker.dataSource = self;
        _classPicker.showsSelectionIndicator = NO;
        _classPicker.backgroundColor=[UIColor whiteColor];
        _classPicker.userInteractionEnabled=YES;
    }
    
    return _classPicker;
}
- (NSMutableArray *)classesArr{
    
    if (_classesArr == nil) {
        
        _classesArr = [NSMutableArray array];
        _classNames = [NSMutableArray array];
    }
    
    return _classesArr;
}

@end
